/**
 * Copyright (c) 2019-2029, wwww.kiwipeach.cn (liuburu@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package open.kiwipeach.autoconfigure.web.config;

import open.kiwipeach.autoconfigure.web.interceptor.BlogViewCountInterceptor;
import open.kiwipeach.autoconfigure.web.resolver.CurrentUserMethodArgumentResolver;
import cn.kiwipeach.blog.database.mapper.CustomBlogMapper;
import open.kiwipeach.autoconfigure.web.filter.xss.XssSqlFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * springmvc拓展类,拓展拦截器，过滤器，监听器等等组件。
 * 在jdk8中可以不用继承该适配器了（WebMvcConfigurerAdapter），直接使用接口即可。
 *
 * @author kiwipeach
 * @since 1.0
 */
@Configuration
public class BlogMvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private CustomBlogMapper customBlogMapper;

    @Autowired
    private CacheManager cacheManager;

    @Value("${server.servlet.context-path}")
    private String contenxPath;

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

    /**
     * 拦截器配置
     *
     * @param registry 注册中心
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        Cache cache = cacheManager.getCache("BLOG_VIEW_COUNT");
        // 拦截器不需要上下文信息
        registry.addInterceptor(new BlogViewCountInterceptor(customBlogMapper, cache))
                .addPathPatterns("/blog/detail/**");
        //registry.addInterceptor(new BlogAccessCountInterceptor())
        //        .addPathPatterns("/**");
    }

    /**
     * 参数解析器配置
     *
     * @param argumentResolvers 参数解析器
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new CurrentUserMethodArgumentResolver());
    }

    /**
     * xss过滤拦截器
     */
    @Bean
    public FilterRegistrationBean xssFilterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new XssSqlFilter());
        filterRegistrationBean.setOrder(1);
        filterRegistrationBean.setEnabled(true);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        Map<String, String> initParameters = new HashMap<>(1);
        initParameters.put("excludeUrlPatterns", "/favicon.ico,/assets/*,/assets_admin/*");
        filterRegistrationBean.setInitParameters(initParameters);
        return filterRegistrationBean;
    }


    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // FIXME 做成可配置的白名单
        //corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedOrigin("null");
        corsConfiguration.addAllowedOrigin("http://localhost:8080");
        corsConfiguration.addAllowedOrigin("http://localhost:63345");
        // 2允许任何头
        corsConfiguration.addAllowedHeader("*");
        // 3允许任何方法（post、get等）
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }


}
